package org.je.io;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import org.je.ufo.PUtil;

/**
 * @author fanyifeng
 */
public class RandomIO
{
	private final String		src;
	private RandomAccessFile	accessFile;
	private FileChannel			channel;

	/**
	 * @param path
	 */
	public RandomIO(String path) {
		src = PUtil.format(path);
		refreshChannel();
	}

	public String getPath() {
		return src;
	}

	public long size() {
		try {
			return channel.size();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * @param bf
	 * @param pos
	 */
	public int read(ByteBuffer bf, long pos) {
		try {
			return channel.read(bf ,pos);
		} catch (IOException ex) {
			throw new RuntimeException("random-read-error",ex);
		}
	}

	/**
	 * @param bf
	 * @param pos
	 */
	public int write(ByteBuffer bf, long pos) {
		try {
			return channel.write(bf ,pos);
		} catch (IOException ex) {
			throw new RuntimeException("random-write-error",ex);
		}
	}

	public void refreshChannel() {
		close();
		try {
			accessFile = new RandomAccessFile(new File(src),"rw");
		} catch (FileNotFoundException ex) {
			throw new RuntimeException(ex);
		}
		try {
			channel = accessFile.getChannel();
		} catch (Exception ex) {
			close();
			accessFile = null;
			channel = null;
			throw new RuntimeException(ex);
		}
	}

	public void close() {
		try {
			if (channel != null)
				channel.close();
		} catch (Exception e) {}
		try {
			if (accessFile != null)
				accessFile.close();
		} catch (Exception e) {}
	}
}
